import { useState, useRef, useEffect } from "react";
import { io } from "socket.io-client";
//自定义的倒计时的 hook
export const useCountDown = (num = 60) => {
  const [count, setCount] = useState(num);
  const timer = useRef(null);
  const [isDown, setIsDown] = useState(false);
  function start() {
    timer.current = setInterval(() => {
      //倒计时自用
      // num--;
      // console.log(num);
      // if (num <= -1) {
      //   clearInterval(timer.current);
      //   setCount(count);
      // } else {
      setIsDown(true);
      setCount((prev) => prev - 1);
      // }
    }, 1000);
  }
  useEffect(() => {
    if (count <= 0) {
      clearInterval(timer.current);
      setIsDown(false);
      setCount(num);
    }
  }, [count, num]);
  useEffect(() => {
    return clearInterval(timer.current);
  }, []);
  return { start, count, isDown };
};

//自定义的防抖的 hook
export const useFd = () => {
  const timer = useRef(null);
  function fd(cb) {
    //狸猫换太子 偷梁换柱
    //...XX 形参中是 REST 参数 拓展运算符
    return (...arg) => {
      //先清除上一个延时器
      clearTimeout(timer.current);
      //在开启下一个
      timer.current = setTimeout(() => {
        cb(...arg);
      }, 500);
    };
  }
  //return 用于防抖的函数
  return fd;
};

//创建  socket 连接
export const useSend = (url, cb) => {
  const socket = useRef(null);
  useEffect(() => {
    //在这里创建聊天的连接
    socket.current = io(url, {
      reconnection: true, // 如果连接不通畅，则会自动重连尝试
      reconnectionAttempts: 5, // 设置重连的次数
      reconnectionDelay: 5000, // 重连的延迟时间 ms
      timeout: 8000, // 超时时间 ms
    });
    socket.current.on("message", cb);
    
    return () => socket.current.close();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
  return socket;
};
